package com.czk.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czk.enums.AuthStatusEnum;
import com.czk.model.user.Patient;
import com.czk.model.user.UserInfo;
import com.czk.vo.user.LoginVo;
import com.czk.vo.user.UserAuthVo;
import com.czk.vo.user.UserInfoQueryVo;
import com.czk.yygh.common.exception.YyghException;
import com.czk.yygh.common.helper.JwtHelper;
import com.czk.yygh.common.result.ResultCodeEnum;
import com.czk.yygh.user.mapper.UserInfoMapper;
import com.czk.yygh.user.service.PatientService;
import com.czk.yygh.user.service.UserInfoService;
import com.czk.yygh.user.utils.ConstantWxPropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/11/18 22:26
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private PatientService patientService;

    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        // 获取输入手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        // 参数校验
        if (phone == null || code == null) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //  判断验证码是否一致
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (!Objects.equals(code, redisCode)) {
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }
        // 绑定手机号
        UserInfo userInfo = null;
        if (!StringUtils.isEmpty(loginVo.getOpenid())) {
            // openid不为空
            // 拿到用户
            userInfo = this.selectWxInfoOpenId(loginVo.getOpenid());
            if (null != userInfo) {
                userInfo.setPhone(phone);
                // 更新
                this.updateById(userInfo);
            } else {
                //
                throw new YyghException(ResultCodeEnum.DATA_ERROR);
            }
        }
        if (userInfo == null) {
            // 进行手机登录
            // 判断是否是第一次登录，手机号查询数据库，是的话录入信息
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("phone", phone);
            userInfo = baseMapper.selectOne(wrapper);
            if (userInfo == null) {
                // 添加
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
        }
        // 校验用户是否警用
        if (userInfo.getStatus() == 0) {
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        // 返回登录信息
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        // 生成token
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return map;
    }

    @Override
    public UserInfo selectWxInfoOpenId(String openid) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("openid", openid);
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        return userInfo;
    }

    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        // 得到user
        UserInfo userInfo = baseMapper.selectById(userId);
        // 设置认证信息
        userInfo.setName(userAuthVo.getName());
        // 其他认证信息
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        // 更新
        baseMapper.updateById(userInfo);
    }

    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParams, UserInfoQueryVo userInfoQueryVo) {
        // 获取条件值
        // 用户名称
        String name = userInfoQueryVo.getKeyword();
        // 认证状态
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        // 用户状态
        Integer status = userInfoQueryVo.getStatus();
        // 开始时间
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        // 结束时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            wrapper.like("name", name);
        }
        if (!StringUtils.isEmpty(status)) {
            wrapper.like("status", status);
        }
        if (!StringUtils.isEmpty(authStatus)) {
            wrapper.like("auth_status", authStatus);
        }
        if (!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time", createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.ge("create_time", createTimeEnd);
        }
        // 查询
        Page<UserInfo> selectPage = baseMapper.selectPage(pageParams, wrapper);
        selectPage.getRecords().forEach(userInfo -> {
            this.packUserInfo(userInfo);
        });
        return selectPage;
    }

    private void packUserInfo(UserInfo userInfo) {
        // 0 1 2 转换为认证中，已认证，或未认证
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        userInfo.getParam().put("statusString", userInfo.getStatus() == 0 ? "锁定" : "正常");
    }

    @Override
    public void lock(Long id, Integer status) {
        if (status == 0 || status == 1) {
            // 得到用户信息
            UserInfo userInfo = baseMapper.selectById(id);
            userInfo.setStatus(status);
            // 加入黑名单 redis
            redisTemplate.opsForSet().add(ConstantWxPropertiesUtil.USER_HEIMINGDAN, id + "");
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> show(Long id) {
        // 创建map
        Map<String, Object> map = new HashMap<>(16);
        // 查询用户信息
        UserInfo userInfo = baseMapper.selectById(id);
        // 转换
        this.packUserInfo(userInfo);
        //
        map.put("userInfo", userInfo);
        // 得到就诊人信息
        List<Patient> patientList = patientService.findAllByUserId(id);
        map.put("patientList", patientList);
        return map;
    }

    @Override
    public void approval(Long userId, Integer authStatus) {
        // 查找 2 审核通过 -1 审核不通过
        if (authStatus == 2 || authStatus == -1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }
}
